const app = getApp();
import { getUser, cardVerify } from '../../api/user.js'; 
Page({

  data: {
    userInfo: {}, // 存储已认证用户信息（含realName/idCard/status）
    authForm: {
      realName: '',     
      idCard: '',       
      frontImg: '',      
      backImg: ''       
    },
    isSubmitting: false,  
    frontImgUrl: '',      
    backImgUrl: '', 
    realNameError: '',
    idCardError: '',
    frontImgError: '',
    backImgError: ''
  },

  onLoad(options) {
    this.checkLoginStatus(); 
  },

  async checkLoginStatus() {
    const token = wx.getStorageSync('token');
    console.log('【认证页】当前缓存的 Token：', token);

    if (!token) {
      wx.showToast({ title: '请先登录', icon: 'none', duration: 1500 });
      setTimeout(() => {
        wx.redirectTo({ url: '/pages/login/login' });
      }, 1500);
      return;
    }

    try {
      wx.showLoading({ title: '验证登录状态...' });
      const res = await getUser(); 
      wx.hideLoading();

      if (res.code === 200) {
        this.setData({
          userInfo: {
            ...res.data,
            realName: res.data.realName || JSON.parse(wx.getStorageSync('userInfo') || '{}').realName || '',
            idCard: res.data.idCard || JSON.parse(wx.getStorageSync('userInfo') || '{}').idCard || '',
            status: res.data.status || '0'
          }
        });
        wx.setStorageSync('userInfo', JSON.stringify(this.data.userInfo));
      } else {
        wx.removeStorageSync('token');
        wx.showToast({ title: '登录已失效，请重新登录', icon: 'none' });
        setTimeout(() => {
          wx.redirectTo({ url: '/pages/login/login' });
        }, 1500);
      }
    } catch (error) {
      wx.hideLoading();
      console.error('【认证页】Token 验证异常：', error);
      wx.showToast({ title: '网络异常，登录态验证失败', icon: 'none' });
    }
  },

  readLocalUserInfo() {
    const localUser = wx.getStorageSync('userInfo');
    if (localUser) {
      const parsedUser = JSON.parse(localUser);
      this.setData({ userInfo: parsedUser });
    } else {
      this.setData({ userInfo: { status: '0', realName: '', idCard: '' } });
      wx.showToast({ title: '用户信息缺失，请完成实名认证', icon: 'none' });
    }
  },

  goToMyDetail() {
    wx.switchTab({
      url: '/pages/myDetail/myDetail',
      fail: (err) => {
        console.error('跳转个人中心失败：', err);
        wx.showToast({ title: '跳转失败，请重试', icon: 'none' });
      }
    });
  },

  handleInput(e) {
    const { key } = e.currentTarget.dataset;
    this.setData({
      [`authForm.${key}`]: e.detail.value.trim(),
      [`${key}Error`]: ''
    });
  },

  handleIdCardInput(e) {
    let value = e.detail.value.replace(/[^0-9Xx]/g, '').toUpperCase();
    if (value.length > 18) value = value.substring(0, 18);
    this.setData({
      'authForm.idCard': value,
      'idCardError': ''
    });
  },

  chooseFrontImg() { this.chooseImage('frontImg'); },
  chooseBackImg() { this.chooseImage('backImg'); },

  chooseImage(type) {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.checkImage(res.tempFilePaths[0], type);
      },
      fail: () => {
        wx.showToast({ title: `选择身份证${type === 'frontImg' ? '正面' : '反面'}失败`, icon: 'none' });
      }
    });
  },

  checkImage(tempPath, type) {
    wx.getImageInfo({
      src: tempPath,
      success: (imgInfo) => {
        if (!['jpeg', 'png'].includes(imgInfo.type)) {
          wx.showToast({ title: '请上传JPG或PNG格式图片', icon: 'none' });
          return;
        }
        if (imgInfo.size > 5 * 1024 * 1024) {
          wx.showToast({ title: '图片大小不能超过5MB', icon: 'none' });
          return;
        }
        this.imageToBase64(tempPath, type, imgInfo.type);
      },
      fail: () => {
        wx.showToast({ title: '图片解析失败，请重试', icon: 'none' });
      }
    });
  },

  imageToBase64(tempPath, type, imgType) {
    wx.getFileSystemManager().readFile({
      filePath: tempPath,
      encoding: 'base64',
      success: (res) => {
        const pureBase64 = res.data;
        const fullBase64 = `data:image/${imgType};base64,${pureBase64}`;
        this.setData({
          [`authForm.${type}`]: pureBase64,
          [`${type}Url`]: fullBase64,
          [`${type}Error`]: ''
        });
        wx.showToast({ title: `身份证${type === 'frontImg' ? '正面' : '反面'}上传成功`, icon: 'success' });
      },
      fail: () => {
        wx.showToast({ title: '图片处理失败，请重试', icon: 'none' });
      }
    });
  },

  clearFrontImg() { this.clearImage('frontImg'); },
  clearBackImg() { this.clearImage('backImg'); },
  clearImage(type) {
    this.setData({
      [`authForm.${type}`]: '',
      [`${type}Url`]: '',
      [`${type}Error`]: ''
    });
  },

  checkRealName() {
    const { realName } = this.data.authForm;
    if (!realName) {
      this.setData({ realNameError: '请输入身份证姓名' });
      return false;
    }
    if (!/^[\u4e00-\u9fa5]{2,20}$/.test(realName)) {
      this.setData({ realNameError: '请输入2-20位中文姓名' });
      return false;
    }
    this.setData({ realNameError: '' });
    return true;
  },

  checkIdCard() {
    const { idCard } = this.data.authForm;
    if (!idCard) {
      this.setData({ idCardError: '请输入18位身份证号' });
      return false;
    }
    if (!/(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(idCard)) {
      this.setData({ idCardError: '请输入有效的18位身份证号' });
      return false;
    }
    this.setData({ idCardError: '' });
    return true;
  },

  checkImages() {
    const { frontImg, backImg } = this.data.authForm;
    let pass = true;
    if (!frontImg) { this.setData({ frontImgError: '请上传身份证正面' }); pass = false; }
    if (!backImg) { this.setData({ backImgError: '请上传身份证反面' }); pass = false; }
    return pass;
  },

  validateForm() {
    return this.checkRealName() && this.checkIdCard() && this.checkImages();
  },

  async submitAuth() {
    if (!this.validateForm()) return;
    if (this.data.isSubmitting) return;
    this.setData({ isSubmitting: true });

    try {
      const { realName, idCard, frontImg, backImg } = this.data.authForm;
      const res = await cardVerify({ 
        name: realName, 
        card: idCard, 
        frontImg: frontImg, 
        backImg: backImg 
      }); 

      if (res.code === 200) {
        const updatedUserInfo = {
          ...this.data.userInfo,
          status: '1',       
          realName: realName,
          idCard: idCard     
        };
        this.setData({ userInfo: updatedUserInfo });
        wx.setStorageSync('userInfo', JSON.stringify(updatedUserInfo));

        wx.showToast({
          title: '实名认证通过',
          icon: 'success',
          duration: 1500,
          success: () => setTimeout(() => this.goToMyDetail(), 1500)
        });
      } else {
        wx.showToast({ title: '认证失败：' + (res.msg || '信息有误'), icon: 'none' });
      }
    } catch (error) {
      console.error('认证接口错误：', error);
      wx.showToast({ title: '网络异常，请稍后重试', icon: 'none' });
    } finally {
      this.setData({ isSubmitting: false });
    }
  },

  hideRealName(name) {
    if (!name) return '已隐藏';
    return name.replace(/(\S)\S+/, '$1**');
  },
  hideIdCard(idCard) {
    if (!idCard) return '已隐藏';
    return idCard.replace(/^(\d{6})(\d{8})(\d{4})$/, '$1********$3');
  },
  onUnload() {
    this.setData({ isSubmitting: false });
  }
});